<template>
  <div style="height: 100%;width: 100%">
    <!-- 搜索筛选 -->
    <el-row :model="formInline" style="height: 5%;width: 100%;display: flex;align-items: center;">
      <el-col :span="0.5" style="margin-right: 0.5vw">
        <el-text size="large">搜索:</el-text>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center;justify-content: center;">
        <el-input size="large" v-model="formInline.userName" placeholder="请输入所属人姓名或手机号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;">
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="searchByNameOrPhone">
          <font-awesome-icon icon="fas fa-search" />
          <span style="margin-left:1vh">查询</span>
        </el-button>
      </el-col>
      <el-col :span="16">
      </el-col>
    </el-row>
    <el-row style="
    background-color: white;
    height: 35%;
    margin-top: 2vh;
    margin-bottom: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
      <filter-list :filter-rows="rows" @updateList="updateList"/>
    </el-row>
    <!-- 分页组件5%-->
    <el-row style="display: flex;justify-content: flex-end;align-items: center;height: 5%;width: 100%;margin-bottom: 10px">
      <el-pagination
          v-model:current-page="pageParam.pageNo"
          v-model:page-size="pageParam.pageSize"
          v-model:total="pageParam.totalCount"
          :page-sizes="[5, 10, 15, 20]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes,prev, pager, next, jumper"
          :total="100"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>
    <!--列表-->
    <el-table
        :header-cell-style=" { background: '#F7FBFE' , color: '#000' , 'text-align': 'center' }"
        size="large"
        :cell-style="{'text-align':'center'}"
        style="width: 100%;height: 50%"
        :data="reportList"
        v-loading="loading"
        highlight-current-row
        element-loading-text="拼命加载中...">
      <!--      <el-table-column align="center" type="selection" width="60">-->
      <!--      </el-table-column>-->
      <el-table-column sortable prop="reportId" label="报告编号" width="150">
      </el-table-column>
      <el-table-column sortable prop="name" label="患者名称" width="150">
      </el-table-column>
      <el-table-column sortable prop="username" label="患者手机号" width="150">
      </el-table-column>
      <el-table-column sortable prop="age" label="患者年龄" width="150">
      </el-table-column>
      <el-table-column sortable prop="sex" label="患者性别" width="150">
      </el-table-column>
      <el-table-column sortable prop="createdDate" label="报告生成时间" width="300">
        <template v-slot="scope">
          {{ formatDateTime(scope.row.createdDate) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" min-width="200">
        <template v-slot="scope">
          <el-button size="large" style="background-color:#edf7f6;color:#4CAF50;"  @click="showReport(scope.row.reportId)">
            <!--
            <font-awesome-icon icon="fas fa-check-circle" />
            <span style="margin-left:1vh">审核</span>-->
            <span v-if ="rows[0].buttons[0].selected">审核</span>
            <span v-if ="rows[0].buttons[1].selected">发布</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--报告弹窗-->
<!--    <report-dialog :currentReportId="currentReportId" :enable-edit="false" :visible="reportVisible"/>-->
    <el-dialog v-model="reportVisible"
               title="睡眠呼吸检测报告"
               align-center
               center
               :style="{ 'height': '100%', 'width': '50vw' }"
               @close="reportClose"
    >
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb">
        <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index" @click="handlePageChange(index + 1)">
          <el-text :class="{ 'active': currentPage === index + 1 }" size="large">{{ item }}</el-text>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <el-text :class="{ 'active': currentPage === 9 }" size="large"></el-text>
        </el-breadcrumb-item>
      </el-breadcrumb>
      <el-container style="display: flex;align-items: center;justify-content: center;flex-direction: column; height: 100%;">
        <!--个人信息-->
        <user-info-card v-if="currentPage === 1" :currentReportId="currentReportId" />
        <!-- 呼吸 -->
        <breath-card v-if="currentPage === 2" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--鼾声-->
        <snore-card v-if="currentPage === 3" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--睡眠状态-->
        <sleep-status-card v-if="currentPage === 4" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--心率-->
        <heart-rate-card v-if="currentPage === 5" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--心律  -->
        <HeartRhythmCard v-if="currentPage === 6" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!-- 体位 -->
        <body-card v-if="currentPage === 7" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--综合评价-->
        <DiagnosisRecord v-if="currentPage === 8" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
      </el-container>
      <!-- 分页和保存按钮 -->
      <el-container v-if="currentPage === 8" class="pagination" style="position: absolute; bottom: 10px; right: 10px;">
        <el-button type="primary" style="margin-left: 10px;background-color: #04c1a5" @click="updateReportState">审核发布</el-button>
        <el-button type="primary" style="margin-left: 10px;background-color: #D32F2F" @click="updateReportStateToNo">审核不发布</el-button>
      </el-container>
      <!--    翻页按钮-->
      <div v-if="reportVisible" class="floating-buttons">
        <el-text style="color: white;font-weight: 700;" size="large" >上一项</el-text>
        <div style="display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 5vh">
          <el-button @click="prev" class="paging_button" :type="'text'">
            <el-icon class="paging_button_icon">
              <ArrowUp />
            </el-icon>
          </el-button >
        </div>
        <div style="display: flex;align-items: center;justify-content: center">
          <el-button @click="next" class="paging_button" :type="'text'">
            <el-icon class="paging_button_icon">
              <ArrowDown />
            </el-icon>
          </el-button>
        </div>
        <el-text style="color: white;font-weight: 700;" size="large">下一项</el-text>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import {onMounted, ref} from 'vue';
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import * as echarts from "echarts";
import UserInfoCard from "@/components/cards/userInfoCard.vue";
import ReferenceType from "@/components/ReferenceType.vue";
import SleepStatusCard from "@/components/cards/sleepStatusCard.vue";
import SnoreCard from "@/components/cards/snoreCard.vue";
import HeartRateCard from "@/components/cards/heartRateCard.vue";
import BreathCard from "@/components/cards/breathCard.vue";
import BodyCard from "@/components/cards/bodyCard.vue";
import DiagnosisRecord from "@/components/cards/diagnosisRecord.vue";
import HeartRhythmCard from "@/components/cards/heartRhythmCard.vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import { ArrowRight } from '@element-plus/icons-vue'
import admin from "@/api/admin.js";
import doctor from "@/api/doctor.js";
import report from "@/api/report.js";
import ReportDialog from "@/components/ReportDialog.vue";
import FilterList from "@/components/tableViews/filterList.vue";
import {useAuthStore} from "@/stores/auth.js";
const loading = ref(false);
const breadcrumbItems = ["个人信息", "呼吸", "鼾声", "睡眠状态", "心率与血氧","心律", "体位", "记录"];
const editForm = ref({

});
const reportList = ref([]);
const formInline = ref({
  userName: '',
});
const pageSize = ref(1);
const authStore = useAuthStore();

//报告编辑与查看
const reportVisible = ref(false);
const currentReportId = ref();
const currentPage = ref(1);
const enableEdit = ref(true)
const showReport = (reportId)=>{
  reportVisible.value = true;
  currentReportId.value = reportId
}
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const updateReportState = () => {
  const updateReportStateDto = {
    reportId: currentReportId.value,
    state: 1
  };
  report.updateState(updateReportStateDto)
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage.success("操作成功");
          reportVisible.value = false
          getReportList();
        }
      })
      .catch((err) => {
        console.log(err);
      });
};
//点击审核不发布将state改为2
const updateReportStateToNo = () =>{
  const updateReportStateToNoDto = {
    reportId: currentReportId.value,
    state: 2
  };
  report.updateState(updateReportStateToNoDto)
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage.success("操作成功");
          reportVisible.value = false
          getReportList();
        }
      })
      .catch((err) => {
        console.log(err);
      });
};
const prev = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};
const next = () => {
  if (currentPage.value < 8) {
    currentPage.value++;
  }
};
const reportClose = ()=>{
  currentPage.value = 1
}

//分页
const handleCurrentChange = (newPage)=>{
  pageParam.value.pageNo = newPage;
  const createReportQuery = {
    status: null,
    sex: null,
    minYear: null,
    maxYear: null,
    minCreatedDate: null,
    maxCreatedDate: null,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
    name: null,
    username: null,
  }
  //更新查询条件
  updateCreateReportQuery(rows.value, createReportQuery);
  //执行查询
  requestReportList(createReportQuery);
}
const handleSizeChange = ()=>{
  const createReportQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  //更新查询条件
  updateCreateReportQuery(rows.value, createReportQuery);
  //执行查询
  requestReportList(createReportQuery);
}
const pageParam = ref({
  pageNo:1,
  pageSize:10,
  totalCount:10,
  totalPages:10,
  nextPage:0,
  prePage:0,
  hasPre:false,
  hasNext:true,
});

//按钮查询过滤
const rows = ref([
  { label: '状态', buttons: [
      { text: '-未审核-',value: 0, selected: true },
      { text: '-审核未发布-',value: 2, selected: false }
    ] },
  { label: '性别', buttons: [
      { text: '-全部-',value:null, selected: true },
      { text: '男',value:'男', selected: false },
      { text: '女',value:'女', selected: false },
    ] },
  { label: '年龄', buttons: [
      { text: '-全部-',value:null, selected: true },
      { text: '0到10岁',value:0, selected: false },
      { text: '11到20岁',value:10, selected: false },
      { text: '21到30岁',value:20, selected: false },
      { text: '31到40岁',value:30, selected: false },
      { text: '51到50岁',value:40, selected: false },
      { text: '51到60岁',value:50, selected: false },
      { text: '60岁以上',value:200, selected: false },
    ] },
  { label: '生成时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: null,selected: false },
    ] }
]);
const adminRows = ref([
  { label: '状态', buttons: [
      { text: '-未审核-',value: 0, selected: true },
      { text: '-审核未发布-',value: 10, selected: false }
    ] },
  { label: '性别', buttons: [
      { text: '-全部-',value:null, selected: true },
      { text: '男',value:'男', selected: false },
      { text: '女',value:'女', selected: false },
    ] },
  { label: '年龄', buttons: [
      { text: '-全部-',value:null, selected: true },
      { text: '0到10岁',value:0, selected: false },
      { text: '11到20岁',value:10, selected: false },
      { text: '21到30岁',value:20, selected: false },
      { text: '31到40岁',value:30, selected: false },
      { text: '51到50岁',value:40, selected: false },
      { text: '51到60岁',value:50, selected: false },
      { text: '60岁以上',value:200, selected: false },
    ] },
  { label: '生成时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: null,selected: false },
    ] }
]);
const updateList = (newRows) =>{
  const createReportQuery = {
    status: null,
    sex: null,
    minYear: null,
    maxYear: null,
    minCreatedDate: null,
    maxCreatedDate: null,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  //调用更新方法
  updateCreateReportQuery(newRows, createReportQuery);
  //执行查询
  requestReportList(createReportQuery);
}

//列表查询
const role = ref('')
onMounted(()=>{
  role.value = authStore.role;
  getReportList();
})
const getReportList = ()=>{
  const createReportQuery = {
    status: 0,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  createReportQuery.status = updateSelectedValue(rows.value[0].buttons);
  requestReportList(createReportQuery)
}
const requestReportList = (createReportQuery) =>{
  loading.value = true;
  doctor.searchCreateReportList(createReportQuery)
      .then((res) => {
        if (res.data.code === 200) {
          reportList.value = res.data.data.result
        }
        updatePageParams(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(()=>{
        loading.value = false
      });
}

// const getReportList2 = ()=>{
//   const createReportQuery = {
//     status: 2,
//     pageIndex: pageParam.value.pageNo - 1,
//     pageSize: pageParam.value.pageSize
//   }
//   requestReportList(createReportQuery)
// }

const updateCreateReportQuery = (rows,createReportQuery)=>{
  createReportQuery.status = updateSelectedValue(rows[0].buttons);
  createReportQuery.sex = updateSelectedValue(rows[1].buttons);
  createReportQuery.minYear = updateSelectedValue(rows[2].buttons);
  createReportQuery.maxYear = updateSelectedValue(rows[2].buttons) + 10;
  createReportQuery.minCreatedDate = updateTime(rows[3].buttons, createReportQuery.currentTime);
  createReportQuery.maxCreatedDate = getCurrentDate();
  if (createReportQuery.minYear===null || createReportQuery.maxYear===null){
    createReportQuery.minYear = null;
    createReportQuery.maxYear = null;
  }
  if (createReportQuery.minCreatedDate===null || createReportQuery.maxCreatedDate===null){
    createReportQuery.minCreatedDate = null;
    createReportQuery.maxCreatedDate = null;
  }
  const userInfo = formInline.value.userName
  if (userInfo !== ''){
    if (userInfo.length === 11){
      createReportQuery.userName = formInline.value.userName
    }else{
      createReportQuery.name = formInline.value.userName
    }
  }
}
function updatePageParams(pageData) {
  pageParam.value.pageNo = pageData.pageNo;
  pageParam.value.pageSize = pageData.pageSize;
  pageParam.value.totalCount = pageData.totalCount;
  pageParam.value.totalPages = pageData.totalPages;
  pageParam.value.nextPage = pageData.nextPage;
  pageParam.value.hasNext = pageData.hasNext;
  pageParam.value.prePage = pageData.prePage;
  pageParam.value.hasPre = pageData.hasPre;
}
function formatDateTime(dateTimeString) {
  const date = new Date(dateTimeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
function updateSelectedValue(buttons) {
  for (const button of buttons) {
    if (button.selected) {
      return button.value;
    }
  }
  return null;
}
function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}// 获取当前时间的字符串，格式为 yyyy-mm-dd
function updateTime(buttons, currentDate) {
  for (const button of buttons) {
    if (button.selected) {
      if (button.value === null) {
        return null;
      } else {
        const time = new Date();
        time.setDate(time.getDate() - button.value);
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }
  }
  return currentDate; // 默认取当前时间
}

//信息查询
const searchByNameOrPhone = ()=>{
  let createReportQuery = {
    status: 0,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  if (formInline.value.userName.length === 11){
    createReportQuery.userName = formInline.value.userName
  }else{
    createReportQuery.name = formInline.value.userName
  }
  requestReportList(createReportQuery)
}
</script>

<style scoped lang="scss">
.breadcrumb {
  margin-left: 5%;
  margin-bottom: 2vh;
  font-size: 1.5vh;
  font-weight: 600;
  cursor: pointer;
}
::v-deep .customer-table th{
  border:none;
}
::v-deep .customer-table td,.customer-table th.is-leaf {
  border:none;
}

::v-deep .el-dialog__header {
  /* background: #002a52; */
  text-align: center;
}
::v-deep .el-dialog__title {
  color: #4CAF50;
  font-size: larger;
  font-weight: 600;
}

.active{
  color: #04c1a5;
}
.floating-buttons {
  position: fixed;
  top: 50%;
  right: 20%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* background-color: white; */
  padding: 10px;
  width: 4vw;
}
.paging_button{
  display: flex;
  align-items: center;
  justify-content: center;

}
.paging_button_icon{
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  font-size: 4.5vw;
  color: #04c1a5;
}
</style>